package com.nanmeishu.services.tale.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nanmeishu.infrastructure.web.entity.ResponseResult;
import com.nanmeishu.services.feign.UserFeign;
import com.nanmeishu.services.tale.entity.AtlasCityCoord;
import com.nanmeishu.services.tale.mapper.AtlasCityCoordMapper;
import com.nanmeishu.services.tale.mapper.StatuMapper;
import com.nanmeishu.services.tale.mapper.TaleDetailsMapper;
import com.nanmeishu.services.tale.mapper.TaleMapper;
import com.nanmeishu.services.tale.entity.Tale;
import com.nanmeishu.services.tale.entity.TaleDetails;
import com.nanmeishu.services.tale.facade.TaleService;

import com.nanmeishu.util.DataUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("taleService")
public class TaleServiceImpl implements TaleService {

    @Autowired
    TaleMapper taleMapper;

    @Autowired
    UserFeign userFeign;

    @Autowired
    TaleDetailsMapper taleDetailsMapper;

    @Autowired
    StatuMapper statuMapper;

    @Autowired
    AtlasCityCoordMapper atlasCityCoordMapper;

    @Transactional
    @Override
    public void saveTaleAndDetails(Tale tale, String userId) {
        saveTaleAndDetailsVerify(tale, userId);
        int i = taleMapper.insert(tale);
        if (i <= 0) {
            throw new RuntimeException("创建时出错了！");
        }
        TaleDetails taleDetails = tale.getTaleDetails();
        taleDetails.setTaleId(tale.getTaleId());
        int insert = taleDetailsMapper.insert(taleDetails);
        if (insert <= 0) {
            throw new RuntimeException("创建时出错了！");
        }
    }

    //新增故事及其明细---数据有效性验证
    private void saveTaleAndDetailsVerify(Tale tale, String userId) {
        DataUtil.verifyData(tale.getFrontDate(), "故事开始日期/frontDate");
        DataUtil.verifyData(tale.getEndDate(), "故事结束日期/endDate");
        if (tale.getCreateTime() == null) {
            tale.setCreateTime(LocalDateTime.now());
        }
        DataUtil.verifyData(tale.getType(), "故事类型/type");
        DataUtil.verifyData(tale.getTaleDetails().getTaleTitle(), "故事标题/taleTitle");
        if (tale.getTaleDetails().getContent() == null) {
            tale.getTaleDetails().setContent("");
        }
        if (tale.getType() == 1 && !tale.getFrontDate().toString().equals(tale.getEndDate().toString())) {
            throw new RuntimeException("日期的开始日期和结束日期都应该在同一天！");
        }
        if (tale.getUserId() == null) {
            ResponseResult userByToken = userFeign.get(userId);
            if (userByToken.getData() == null || userByToken.getData().equals("")) {
                throw new RuntimeException("所属用户必须是合法用户");
            } else {
                tale.setUserId(Long.parseLong(userId));
            }
        }
    }

    @Override
    public Map<String, Object> listByUserId(String userId, String pageNum, String pageSize) {
        Map<String, Object> map = new HashMap<>();
        IPage<Tale> page = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        IPage<Tale> taleIPage = taleMapper.selectPage(page, new QueryWrapper<Tale>()
                .eq("user_id", userId)
                .eq("type",0)
                .orderByDesc("create_time"));
        List<Tale> taleList = taleIPage
                .getRecords();
        for (Tale tale : taleList) {
            tale.setTaleDetails(taleDetailsMapper.selectOne(new QueryWrapper<TaleDetails>().eq("tale_id", tale.getTaleId())));
        }
        map.put("tales", taleList);
        map.put("total", taleIPage.getTotal());
        return map;
    }

    @Transactional
    @Override
    public void updateTaleAndDetails(Tale tale) {
        int i = taleMapper.updateById(tale);
        if (i <= 0) {
            throw new RuntimeException("更新出错");
        }
        TaleDetails taleDetails = tale.getTaleDetails();
        if (taleDetails == null || taleDetails.getTaleDetailsId() == null) {
            return;
        }
        int i1 = taleDetailsMapper.updateById(taleDetails);
        if (i1 <= 0) {
            throw new RuntimeException("更新出错");
        }
    }

    @Override
    public Integer countTaleByUserId(String userId) {
        return taleMapper.selectCount(new QueryWrapper<Tale>().eq("type", 0).eq("user_id", userId));
    }

    @Override
    public void deleteTale(String userId, String taleId) {
        int delete = taleMapper.delete(new QueryWrapper<Tale>().eq("user_id", userId).eq("tale_id", taleId));
        if (delete <= 0) {
            throw new RuntimeException("删除出错");
        }
    }

    @Override
    public Tale getTale(String taleId) {
        Tale tale = taleMapper.selectById(taleId);
        tale.setTaleDetails(taleDetailsMapper.selectOne(new QueryWrapper<TaleDetails>().eq("tale_id", tale.getTaleId())));
        tale.setStatu(statuMapper.selectById(tale.getObjectt()));
        return tale;
    }

    @Override
    public String caiHongPiText() {
        String text = taleMapper.caiHongPiText();
        return text;
    }

    @Override
    public void signTaleDitu(Tale tale, String userId) {
        tale.setCreateTime(LocalDateTime.now());
        tale.setType(4);
        tale.setUserId(Long.parseLong(userId));
        //通过名称获取城市Id
        String cityName = tale.getCityName();
        QueryWrapper<AtlasCityCoord> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.like("city_name", cityName + "%");
        AtlasCityCoord atlasCityCoord = atlasCityCoordMapper.selectOne(objectQueryWrapper);
        if (atlasCityCoord == null) {
            throw new RuntimeException("所选城市不存在");
        }
        tale.setObjectt(atlasCityCoord.getId().toString());
        taleMapper.insert(tale);
    }

    @Override
    public List<String> listCityName(String userId) {
        List<String> atlasCityCoords=atlasCityCoordMapper.listCityName(userId);
        return atlasCityCoords;
    }

    @Override
    public List<Tale> listTaleByDitu(String userId, String dituName) {
        List<Tale> tales=taleMapper.listTaleByDitu(userId,dituName);
        return tales;
    }

    @Override
    public void saveTaleDetails(TaleDetails taleDetails) {
        if(taleDetails.getTaleDetailsId()==null){
            // 新增
            taleDetailsMapper.insert(taleDetails);
        }else {
            //修改
            taleDetailsMapper.updateById(taleDetails);
        }
    }
}
